package com.yao.club.service.impl;

import com.netease.yidun.sdk.core.utils.StringUtils;
import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.PostsCommentLikeRecord;
import com.yao.club.entity.dto.SysImg;
import com.yao.club.entity.request.CommentLikeRequestEntity;
import com.yao.club.entity.request.CommentRequestEntity;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.entity.vo.PostsCommentVO;
import com.yao.club.entity.vo.PostsInfoVO;
import com.yao.club.mapper.PostsCommentMapper;
import com.yao.club.mapper.PostsInfoMapper;
import com.yao.club.mapper.PostsTopicMapper;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.PostsCommentLikeRecordRepository;
import com.yao.club.reposittory.SysImageRepository;
import com.yao.club.service.PostsCommentService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PostsCommentServiceImpl implements PostsCommentService {

    @Resource
    PostsInfoMapper postInfoMapper;
    @Autowired
    SysImageRepository sysImageRepository;
    @Resource
    PostsTopicMapper topicMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    PostsCommentMapper postsCommentMapper;

    @Autowired
    PostsCommentLikeRecordRepository commentLikeRepository;




    /**
     * 分页获得帖子评论信息
     */
    public ResponseEntity<ResultEntity> pageComment(String postsId, int pageNum, int pageSize){
        ResultEntity postsCommentEntity = new ResultEntity();

        int total = postsCommentMapper.countCommentsByPostsId(postsId);
        postsCommentEntity.total = total;
        postsCommentEntity.size = pageSize;
        postsCommentEntity.current = pageNum;
        postsCommentEntity.records = getCommentsByPostsId(postsId);
        return ResponseUtils.success(postsCommentEntity);
    }


    public List<PostsCommentVO> getCommentsByPostsId(String postsId) {
        // 获取一级评论
        List<PostsCommentVO> firstLevelComments = postsCommentMapper.selectFirstLevelComments(postsId);

        // 为每个一级评论获取二级评论
        firstLevelComments.forEach(comment -> {
            // 获取二级评论
            List<PostsCommentVO> secondLevelComments = postsCommentMapper.selectSecondLevelComments(comment.posts_comment_id);

            // 设置头像信息
            if (comment.head_img_id != null) {
                SysImg headImg = postsCommentMapper.selectHeadImgById(comment.head_img_id);
                comment.headImg = headImg;
            }

            // 为二级评论设置头像信息
            secondLevelComments.forEach(subComment -> {
                if (subComment.head_img_id!= null) {
                    SysImg headImg = postsCommentMapper.selectHeadImgById(subComment.head_img_id);
                    subComment.headImg = headImg;
                }
            });

            comment.twoLevel = secondLevelComments;
        });

        return firstLevelComments;
    }


    /**
     * 发布评论
     * @param request
     * @param username
     * @return
     */
    public ResponseEntity<Boolean> addComment(CommentRequestEntity request,String username) {

        UserEntity currentUser = userMapper.select(username);
        // 构建评论实体
        PostsCommentVO comment = new PostsCommentVO();
        comment.setPosts_id(request.getPostsId());
        comment.setFirst_comment_id("0"); // 一级评论first_comment_id为0
        comment.setParent_id("0"); // 一级评论parent_id为0
        comment.setContent(request.getContent());
        comment.setCreate_by(currentUser.getMember_id()+"");
        comment.setCreate_name(currentUser.getNickname());
        comment.setHead_img_id(currentUser.getAvatar_id()+"");
        comment.setLevel(1); // 一级评论

        // 敏感词过滤
        comment.setIf_sensitive(true);
        PostsInfoVO postsInfoEntity = postInfoMapper.select(request.getPostsId());
        comment.setBe_reply_id(postsInfoEntity.create_by);

        UserEntity userEntity = userMapper.getUserByMemberId(postsInfoEntity.create_by);
        comment.setReply_name(userEntity.nickname);
        // 保存到数据库
        //posts_id,first_comment_id,parent_id,content,create_by,create_name,head_img_id,level,if_sensitive,create_time
        postsCommentMapper.addComment(comment.posts_id,comment.first_comment_id,comment.parent_id,comment.content,comment.create_by,comment.create_name,comment.head_img_id,comment.level,comment.if_sensitive,comment.reply_name,comment.be_reply_id);

        // 更新帖子评论数
        postInfoMapper.incrementCommentCount(request.getPostsId());

        return ResponseUtils.success(true);

    }

    /**
     * 发布评论
     * @param commentRequest
     * @param username
     * @return
     */
    public ResponseEntity<Boolean> replyComment(CommentRequestEntity commentRequest,String username) {
        UserEntity currentUser = userMapper.select(username);
        // 构建评论实体
        PostsCommentVO reply = new PostsCommentVO();
        reply.setPosts_id(commentRequest.getPostsId());
        reply.setParent_id(commentRequest.getParentId());
        reply.setContent(commentRequest.getContent());
        reply.setCreate_by(currentUser.getMember_id()+"");
        reply.setCreate_name(currentUser.getNickname());
        reply.setHead_img_id(currentUser.getAvatar_id()+"");
        reply.setLevel(2); // 二级评论

        // 设置被回复人信息
        if (StringUtils.isNotEmpty(commentRequest.getBeReplyId())) {
            reply.setBe_reply_id(commentRequest.getBeReplyId());
            UserEntity beReplyUser = userMapper.getUserByMemberId(commentRequest.getBeReplyId());
            reply.setReply_name(beReplyUser.getNickname());
        }

        // 设置一级评论ID
        if (StringUtils.isNotEmpty(commentRequest.getFirstCommentId())) {
            reply.setFirst_comment_id(commentRequest.getFirstCommentId());
        }
        // 敏感词过滤
        reply.setIf_sensitive(true);
        // 保存到数据库
        postsCommentMapper.addComment(reply.posts_id,reply.first_comment_id,reply.parent_id,reply.content,reply.create_by,reply.create_name,reply.head_img_id,reply.level,reply.if_sensitive,reply.reply_name,reply.be_reply_id);
        // 更新一级评论的评论数
        postInfoMapper.incrementCommentCount(commentRequest.getPostsId());
        return ResponseUtils.success(true);
    }

    /**
     * 点赞评论
     * @param commentRequest
     * @param username
     * @return
     */
    public ResponseEntity<Boolean> giveLike(CommentLikeRequestEntity commentRequest, String username) {
        UserEntity userEntity = userMapper.select(username);
        PostsCommentLikeRecord existingLike = commentLikeRepository.selectLikeByPostsId(commentRequest.getPostsId(),userEntity.member_id,commentRequest.getCommentId());

        if (existingLike != null && existingLike.getStatus().equals(PostsCommentLikeRecord.ACTIVE) ) {
            // 已经点赞
            return ResponseUtils.failed("已经点赞");
        }

        PostsCommentLikeRecord like;
        if (existingLike != null) {
            // 取消点赞后再次点赞
            existingLike.setStatus(PostsCommentLikeRecord.ACTIVE);
            commentLikeRepository.save(existingLike);
        } else {
            like = new PostsCommentLikeRecord();
            like.setPostsId(commentRequest.getPostsId());
            like.setPostsCommentId(commentRequest.getCommentId());
            like.setStatus(PostsCommentLikeRecord.ACTIVE);
            like.setUserId(userEntity.getMember_id()+"");
            commentLikeRepository.save(like);
        }

        // 更新评论的点赞数
        postsCommentMapper.incrementCommentCount(commentRequest.getCommentId());
        return ResponseUtils.success(true);
    }

    /**
     * 取消点赞评论
     * @param commentRequest
     * @param username
     * @return
     */
    public ResponseEntity<Boolean> giveLikeNo(CommentLikeRequestEntity commentRequest, String username) {
        UserEntity userEntity = userMapper.select(username);
        PostsCommentLikeRecord existingLike = commentLikeRepository.selectLikeByPostsId(commentRequest.getPostsId(),userEntity.member_id,commentRequest.getCommentId());

        if (existingLike == null || existingLike.getStatus().equals(PostsCommentLikeRecord.INACTIVE)) {
            // 已经取消点赞
            return ResponseUtils.failed("已经取消点赞");
        }

        if (existingLike != null) {
            // 取消点赞后再次点赞
            existingLike.setStatus(PostsCommentLikeRecord.INACTIVE);
            commentLikeRepository.save(existingLike);
        }
        // 更新评论的点赞数
        postsCommentMapper.unincrementCommentCount(commentRequest.getCommentId());
        return ResponseUtils.success(true);
    }

    /**
     * 删除帖子
     * @param commentId
     * @param username
     * @return
     */
    public ResponseEntity<Boolean> deleteComment(String commentId, String username) {
        UserEntity userEntity = userMapper.select(username);
        int i = postsCommentMapper.deleteComment(commentId,userEntity.getMember_id()+"");
        if (i > 0){
            return ResponseUtils.success(true);
        }
        return ResponseUtils.failed("删除失败");
    }
}
